/*
 * luabase_api.c
 *
 * Copyright (C) 2011 - Dr.NP
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @version luabase_api.c 1.0.0
 * @package exts/luabase
 * @author Dr.NP <np@bsgroup.org>
 * @update 06/14/2011
 */

/**
 * Standard lua functions for luabase
 *
 * === CHANGELOG ===
 * [06/14/2011] - Creation
 */

#include "bsp.h"
#include "luabase_api.h"
#include "bsp_core.h"

#include <stdio.h>
#include <string.h>
#include <sys/types.h>

#include "lua.h"

int luabase_api_send(lua_State *l)
{
    static int cmd_id, clt_id;
    static size_t cblen, rlen;
    static char i_buff[4];
    
    if (!lua_istable(l, -1) || !lua_isnumber(l, -2) || !lua_isnumber(l, -3))
    {
        dump_stack(l);
        lua_pop(l, 3);

        // Wrong parameter type
        debug_info("Wrong parameter type\n");
        return 0;
    }
    
    // pack data into stream
    struct abuff_t *ab = new_abuff();
    luabase_bsp_pack(l, ab);

    lua_pop(l, 1);

    cmd_id = lua_tointeger(l, -1);
    clt_id = lua_tointeger(l, -2);

    lua_pop(l, 2);

    put_u_int(i_buff, cmd_id);
    append_client(clt_id, i_buff, 4);
    put_u_int(i_buff, ab->data_size);
    append_client(clt_id, i_buff, 4);
    append_client(clt_id, (const char *) ab->buff, ab->data_size);
    //debug_hex_data(ab->buff, ab->data_size);

    lua_pushinteger(l, ab->data_size + 8);
    free_abuff(ab);

    return 1;
}

int luabase_api_echotest(lua_State *l)
{
    if (!lua_isstring(l, -1))
    {
        lua_pop(l, 1);

        return 0;
    }

    printf("LUA SAY : %s\n", lua_tostring(l, -1));

    lua_pop(l, 1);

    return 0;
}
